<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use app\model\EnterpriseMember;
use think\db\exception\DbException;
use think\Exception;
use think\Model;
use think\Request;
use think\response\Json;

class Permission extends BaseController
{
    protected Model $model;
    public function initialize(): void
    {
        $this->model = new \app\model\Permission();
    }
    public function index(): Json
    {
        //查询权限列表
        try {
            $data = $this->model->select()->toArray();
            //根据pid值遍历
            $result = [];
            //根据pid遍历，如果不在children则删除children
            array_map(function ($item) use (&$result) {
                if ($item['pid'] == 0) {
                    $result[] = $item;
                } else {
                    foreach ($result as $key => $value) {
                        if ($value['id'] == $item['pid']) {
                            $result[$key]['children'][] = $item;
                        }
                    }
                }
            }, $data);
            return $this->result(200,'权限列表',$result);
        }catch (DbException $e){
            return $this->result($e->getCode(),$e->getMessage());
        }
    }
    public function keys(Request $request): Json
    {
        $payload = $request->get();
        try {
            $getRoleId = (new EnterpriseMember())
                ->where('enterprise_id',$payload['enterprise_id'])
                ->where('user_id',$payload['user_id'])
                ->column('role_id');
            $permId = (new \app\model\Role())->whereIn('id',$getRoleId)->column('permissions');
            $result =[];
            if ($permId){
                $permId = implode(',',$permId);
                $result = $this->model->whereIn('id',$permId)->column('key');
            }
            return $this->result(200,'权限列表',$result);
        } catch (\Exception $e) {
            return $this->result($e->getCode(),$e->getMessage());
        }
    }
    public function save(Request $request): Json
    {
        $payload = $request->post();
        try {
            $isKey = $this->model->where('key',$payload['key'])->find();
            if ($isKey){
                return $this->result(400,'权限已存在');
            }
            $this->model->create($payload);
            return $this->result(200,'保存成功');
        }catch (\Exception $e){
            return $this->result($e->getCode(),$e->getMessage());
        }
    }
    public function delete($id): Json
    {
        try {
            $this->model->where('id',$id)->delete();
            return $this->result(200,'删除成功');
        }catch (\Exception $e){
            return $this->result($e->getCode(),$e->getMessage());
        }
    }
}
